#!/usr/bin/python
import os
import sys

from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader

def ConvertImageFolderToPDF(folderPath):
	supported_filetypes = ( '.jpg', '.png', 'bmp' )
	resultPDFFileName = folderPath + '.pdf'

	imageFileNames = [ os.path.join(folderPath, imageFileName) for imageFileName in os.listdir(folderPath) if os.path.splitext(imageFileName)[1] in supported_filetypes]
	imageFileNames.sort()
	pdfFileNames = []

	for imageFileName in imageFileNames:
		try:
			image = Image.open(imageFileName)
			pdfFileName = imageFileName + '.pdf'
			if os.path.exists(pdfFileName):
				os.remove(pdfFileName)
			image.save(pdfFileName)
			image.close()
			pdfFileNames.append(pdfFileName)
		except IOError:
			pass # Ignore invalid file error

	pdfFileWriter = PdfFileWriter()
	for pdfFileName in pdfFileNames:
		pdfFileReader = PdfFileReader(pdfFileName)
		page = pdfFileReader.getPage(0)
		pdfFileWriter.addPage(page)

	with open(resultPDFFileName, 'wb') as pdfFile:
		pdfFileWriter.write(pdfFile)

	for pdfFileName in pdfFileNames:
		os.remove(pdfFileName)

if __name__ == '__main__':
	ConvertImageFolderToPDF(sys.argv[1])
